import { addItem, getSchool } from "@/api/index";
import { showToast } from "@/util/index";
Page({
  data: {
    price: "",
    content: "",
    campusId: "",
    keyShow: false,
    fileList: [],
    type: "",
    categories: [
      "书籍资料",
      "电子数码",
      "洗漱日化",
      "鞋包服饰",
      "票卡转让",
      "代步工具",
      "体育器材",
      "仙女集市",
      "食品零食",
      "学习用品",
      "电器家具",
      "其他",
    ],
  },
  onContentInput(e: WechatMiniprogram.Input) {
    this.setData({
      content: e.detail.value,
    });
  },
  input(e: { detail: string }) {
    let newPrice = this.data.price + e.detail;
    if (e.detail === ".") {
      if (this.data.price.includes(".") || this.data.price === "") {
        return;
      }
      this.setData({
        price: newPrice,
      });
    } else {
      const regex = /^(0(?:\.\d{0,2})?|([1-9]\d{0,5})(?:\.\d{0,2})?)$/;
      if (parseFloat(newPrice) > 1000000) {
        return;
      }
      this.setData({
        price: regex.test(newPrice) ? newPrice : this.data.price,
      });
    }
  },
  del() {
    let newPrice = this.data.price.slice(0, -1);
    this.setData({
      price: newPrice,
    });
  },
  edit() {
    this.setData({
      keyShow: true,
    });
  },
  selector(e: WechatMiniprogram.CustomEvent) {
    const selectedType = e.currentTarget.dataset.type as string;
    if (this.data.type === selectedType) {
      this.setData({
        type: "",
      });
    } else {
      this.setData({
        type: selectedType,
      });
    }
  },
  upload(e) {
    this.data.fileList = e.detail.value;
  },
  async confirm() {
		if (this.data.content.length <= 5) return showToast("字数不能少于 5 个字");
    await addItem({
      id: this.data.campusId,
      amount: Number.parseInt(this.data.price * 100),
      category: this.data.type,
      description: this.data.content,
      images: this.data.fileList,
    });
    if (this.data.fileList.length === 0) {
      showToast("发布成功");
    } else {
      showToast("发布成功，等待审核");
    }
    wx.navigateBack();
  },
  onLoad() {
    wx.getFuzzyLocation({
      success: async (res) => {
        try {
          const data = await getSchool({
            latitude: res.latitude,
            longitude: res.longitude,
          });
          this.setData({
            campusId: data[0]._id,
          });
        } catch (error) {
          wx.showToast({ title: "定位失败", icon: "none" });
        }
      },
      fail: (err) => {
        wx.showToast({ title: "请授权地理位置", icon: "none" });
      },
    });
  },
});
